package com.sanil.sample.ddb.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sanil.sample.ddb.entity.SysDataSource;
import com.sanil.sample.ddb.service.ISysDataSourceService;
import com.snail.common.dyd.DataSourceInfoProvider;
import com.snail.common.dyd.bean.DataSourceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ddb")
@Slf4j
public class CommonController implements DataSourceInfoProvider {

    @Autowired
    private ISysDataSourceService dataSourceService;

    private static String key = "JEECGBOOT1423670";

    @RequestMapping("/hello")
    public String hello() {
        return "Hello from DDB";
    }


    @GetMapping("/getDbSourceById")
    public SysDataSource getDynamicDbSourceById(String dbSourceCode) {
        String currentDataSource = DynamicDataSourceContextHolder.peek();
        log.info(String.format("currentDataSource:", currentDataSource));
        SysDataSource dbSource = null;
        try{
            DynamicDataSourceContextHolder.push("master");
            dbSource = dataSourceService.getOne(new LambdaQueryWrapper<SysDataSource>().eq(SysDataSource::getCode, dbSourceCode));
            if(dbSource!=null ){
                String dbPassword = dbSource.getDbPassword();
                String decodedStr = jiemi(dbPassword);
                dbSource.setDbPassword(decodedStr);
            }
        }finally {
            DynamicDataSourceContextHolder.push("currentDataSource");
        }
        return dbSource;
    }

    public static String jiemi(String encryptResultStr){
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
        //解密为字符串
        String decryptResult = aes.decryptStr(encryptResultStr, CharsetUtil.CHARSET_UTF_8);
        return  decryptResult;
    }


    @Override
    public DataSourceInfo getDataSourceInfo(String dataSourceId) {
        SysDataSource sysDataSource = getDynamicDbSourceById(dataSourceId);
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        dataSourceInfo.setDbType(Integer.parseInt(sysDataSource.getDbType()));
        dataSourceInfo.setUrl(sysDataSource.getDbUrl());
        dataSourceInfo.setUsername(sysDataSource.getDbUsername());
        dataSourceInfo.setPassword(sysDataSource.getDbPassword());
        dataSourceInfo.setDriverClassName(sysDataSource.getDbDriver());
        dataSourceInfo.setId(sysDataSource.getId());
        return dataSourceInfo;
    }
}
